package cn.stylefeng.guns.modular.cb.controller;

import cn.stylefeng.guns.modular.cb.service.FastDFSService;
import cn.stylefeng.roses.kernel.model.response.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件管理接口
 */
@RestController
@RequestMapping("/api/fastdfs")
public class FileController {

    private static Logger logger = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FastDFSService fastDFSService;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @RequestMapping("/upload_file")
    public ResponseData uploadFile(MultipartFile file) {
        logger.info("upload_file: {}", file.getOriginalFilename());
        String fileId = fastDFSService.uploadFile(file);
        return ResponseData.success(fileId);
    }

    /**
     * 文件下载
     * @param fileId
     * @return
     */
    @RequestMapping("/download_byte")
    public ResponseData downloadByte(String fileId) {
        logger.info("download_byte: {}", fileId);
        byte[] bytes = fastDFSService.downloadByte(fileId);
        return ResponseData.success(bytes);
    }

    /**
     * 文件下载
     * @param fileId
     * @return
     */
    @RequestMapping("/download_file")
    public ResponseData downloadFile(String fileId, HttpServletResponse response) {
        logger.info("download_file: {}", fileId);
        try {
            //获取文件名
            String fileName = fileId.substring(fileId.lastIndexOf('/'));
            //获取页面输出流
            ServletOutputStream outputStream = response.getOutputStream();
            //读取文件
            byte[] bytes = fastDFSService.downloadByte(fileId);
            //向输出流写文件
            //写之前设置响应流以附件的形式打开返回值,这样可以保证前边打开文件出错时异常可以返回给前台
            response.setHeader("Content-Disposition","attachment;filename="+fileName);
            outputStream.write(bytes);
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            logger.error("download_file error: ", e);
        }
        return ResponseData.success();
    }

    /**
     * 显示
     * @param fileId
     * @return
     */
    @GetMapping("/stream_file")
    public void streamFile(String fileId, HttpServletResponse response) {
        logger.info("stream_file: {}", fileId);
        byte[] bytes = fastDFSService.downloadByte(fileId);
        try (ServletOutputStream servletOutputStream = response.getOutputStream();
             InputStream is = new ByteArrayInputStream(bytes);){
            response.setContentLength(bytes.length);
            byte[] buffer = new byte[5120];
            int len = 0;
            while ((len = is.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除
     * @param fileId
     * @return
     */
    @RequestMapping("/delete_file")
    public ResponseData deleteFile(String fileId) {
        logger.info("deleteFile: {}", fileId);
        fastDFSService.deleteFile(fileId);
        return ResponseData.success();
    }
}
